import clientPromise from "@/lib/mongodb";
import { NextResponse } from "next/server";

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const ts_code = searchParams.get("ts_code") || "SZSE.300995";
  const bob_date = searchParams.get("bob_date") || "2025-08-21";

  try {
    const client = await clientPromise;
    const db = client.db("stock_data"); // 你的数据库名
    const collection = db.collection("stock_minute_line");

    const cursor = collection.find({ ts_code, bob_date }).sort({ bob_bj: 1 });

    const data = await cursor.toArray();

    // 转成 chart 可用的数据格式
    const chartData = data.map((row) => ({
      time: Math.floor((new Date(row.bob_bj).getTime()) / 1000), // 秒级时间戳
      open: row.open,
      high: row.high,
      low: row.low,
      close: row.close,
      volume: row.volume,
    }));

    return NextResponse.json(chartData);
  } catch (err) {
    console.error(err);
    return NextResponse.json({ error: "Database query failed" }, { status: 500 });
  }
}
